package com.jbm.core.common;

import com.jbm.core.client.MainCallback;
import com.jbm.core.client.PlayCallback;
import com.jbm.core.iface.*;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;

import java.net.InetSocketAddress;
import java.util.Random;

/**
 * Created by root on 17-2-14.
 */
public class P2PServer
{
	public static final P2PServer g_p2pserver = new P2PServer();

	protected NioDatagramAcceptor m_p2pacceptor;
	protected PlayCallback m_playcallback;

	protected char m_server_type;

	protected String m_serverhost;
	protected int m_serverport;
	protected int m_localport;

	public P2PServer()
	{
	}

	public void Init(String config,
	                 String serverhost,
	                 int serverport,
	                 char server_type,
	                 PlayCallback callback )
	{
		m_server_type = server_type;
		m_playcallback = callback;

		if ( m_server_type == MainServer.Server_type_Server)
		{
			m_localport = 1910;
		}else
		{
			Random r = new Random();
			m_localport = (int)(r.nextInt(8000)+2000);

			m_serverhost = serverhost;
			m_serverport = serverport;
		}

		m_p2pacceptor = new NioDatagramAcceptor();
		m_p2pacceptor.setHandler(new P2PHandler(m_playcallback));

		DefaultIoFilterChainBuilder chain = m_p2pacceptor.getFilterChain();
		chain.addLast("logger", new LoggingFilter());
		DatagramSessionConfig dcfg = m_p2pacceptor.getSessionConfig();
		dcfg.setReuseAddress(true);

		try
		{
			m_p2pacceptor.bind(new InetSocketAddress(m_localport));
		}catch (Exception e)
		{
		}

		if ( m_server_type == MainServer.Server_type_Client )
		{
			ConnectAgent ca = new ConnectAgent("app_server",m_serverhost,m_serverport,m_localport,MainServer.Server_type_Client);

			AccountCtrl.g_accountctrl.PushPoint(AccountCtrl.Account_Server_id,ca);

			AccountCtrl.g_accountctrl.Connect2Point(AccountCtrl.Account_Server_id,"app_server");
		}
	}

	public int getM_localport()
	{
		return m_localport;
	}

	public char getM_server_type()
	{
		return m_server_type;
	}

	public NioDatagramAcceptor getM_p2pacceptor()
	{
		return m_p2pacceptor;
	}
}
